package com.flca.frw.validator
{
	import com.flca.frw.util.ConversionUtil;
	import com.flca.frw.util.DateUtil;
	
	import mx.validators.ValidationResult;
	import mx.validators.Validator;

/*
This validator validates a Date on a given minimum and/or maximum date
For example to test that somenone is between 18 en 65 years:

 	<vld:DateValidator id="vldGeboorteDatum" source="{tiGeboorteDatum}" property="text" required="true" enabled="false"
  			minDate="{minimumDate()}" maxDate="{maximumDate()}" />

		protected function minimumDate() : String {
			var date:Date = DateUtil.plusYear(new Date(), -65);
			return ConversionUtil.dateToString(date);
		}

		protected function maximumDate() : String {
			var date:Date = DateUtil.plusYear(new Date(), -18);
			return ConversionUtil.dateToString(date);
		}
	}

*/
	public class DateValidator extends Validator
	{

		[Inspectable]
		public var minDate : String;
		
		[Inspectable]
		public var maxDate : String;

		public function DateValidator() 
		{
			super();
		}
		
	    override protected function doValidation(value : Object):Array 
	    {
			var results:Array = [];
		
		    // Call base class doValidation().
		    if (required) {
			    results = super.doValidation(value);        
			    if (results.length > 0) { 
		        	return results;
		    	}	
		    } 

	    	//test only if something is filled in
			var testdate:Date = ConversionUtil.stringToDate(value as String);
			if (testdate != null) {
	    		results = validateDate(testdate);
	  		}
						    	
		    return results;
		}
		
		
		private function validateDate(testdate:Date) : Array 
		{
			var result : Array = [];
			
			if (minDate != null) {
				var minimumDate:Date = ConversionUtil.stringToDate(minDate);
				if (testdate < minimumDate) {
			        result.push(
			        	new ValidationResult(true, null, "Datum", 
			            "moet groter zijn dan: " + DateUtil.formatDate(minimumDate)));
		    	    return result;
				}
			}		    

			if (maxDate != null) {
				var maximumDate:Date = ConversionUtil.stringToDate(maxDate);
				if (testdate > maximumDate) {
			        result.push(
			        	new ValidationResult(true, null, "Datum", 
			            "moet kleiner zijn dan: " + DateUtil.formatDate(maximumDate)));
		    	    return result;
				}
			}		    
			
			return result;
		}
	}
}

